package com.fas.system.service.impl;

import com.fas.common.utils.file.FileUtils;
import com.fas.system.enums.TemplateEnum;
import com.fas.system.service.ITemplateService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.FileNotFoundException;

@Service
public class TemplateServiceImpl implements ITemplateService {

    private static final Logger log = LoggerFactory.getLogger(TemplateServiceImpl.class);

    @Override
    public void downloadTemplate(HttpServletResponse response, Integer type) {

        String[]  strings= TemplateEnum.getNameByValue(type);
        if (strings.length > 0){
            String path = "";
            String fileName = strings[0];
            try {
                File file = new File("");
                path = file.getCanonicalPath();
                String downloadPath = path + File.separator + "doc" + File.separator + fileName;

                System.out.println("下载地址： " + (path + File.separator + "doc" + File.separator + fileName));
                if (!new File(downloadPath).exists())
                    throw new FileNotFoundException();
                // 下载名称
                response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
                FileUtils.setAttachmentResponseHeader(response, strings[1]);
                FileUtils.writeBytes(downloadPath, response.getOutputStream());
            } catch (Exception e){
                e.printStackTrace();
            }
        }else {
            log.error("下载的文件模板不存在");
        }
    }
}
